<template>
    <div class="flex-container">
      <div class="map-container">
        <img 
          :src="mapSrc"
          class="map-image"
          alt="Campus Map"
          @click="handleClick"
        />
        <div 
          v-for="(point, index) in points" 
          :key="index"
          class="marker"
          :style="{ left: point.x + 'px', top: point.y + 'px' }"
        ></div>                                             
        <div v-for="facility in facilities" :key="facility.id" class="facility" :style="getFacilityStyle(facility)">
          <div class="facility-name">{{ facility.name }}</div>
        </div>
      </div>
      <div class="controls">
    <!-- 当前地图的大小 -->
      <div>
        <span>当前地图大小:</span>
        <span>{{ imageWidth }} x {{ imageHeight }}</span>
      </div>
      <el-button type="primary" @click="startCreating">开始录入设施</el-button>
      <el-button type="primary" @click="endCreating" :disabled="!isCreating">结束</el-button>
      
      <div v-if="isCreating">
        <h3>输入设施信息</h3>
        <el-form :model="facilityForm" ref="facilityFormRef" label-width="100px">
          <el-form-item label="设施名称" prop="name" :rules="[{ required: true, message: '请输入设施名称', trigger: 'blur' }]">
            <el-input v-model="facilityForm.name" placeholder="设施名称" />
          </el-form-item>
          <el-form-item label="设施描述" prop="description" :rules="[{ required: true, message: '请输入设施描述', trigger: 'blur' }]">
            <el-input v-model="facilityForm.description" placeholder="设施描述" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitFacility">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, reactive } from 'vue';
  import mapImage from '@/assets/images/cduNew.png'; // 使用 import 引入图片
  import { listFacilities,addFacility } from "@/api/pages/facility";
  
  const mapSrc = mapImage;
  const points = ref([]);
  const imageWidth = ref(0);
  const imageHeight = ref(0);
  const loading = ref(false);
  const facilities = ref([]);
  const isCreating = ref(false);
const facilityName = ref("");
const facilityVertices = ref([]); // 存储设施顶点
  const queryParams = reactive({
    name: "",
    type: undefined,
  });
  const facilityForm = reactive({
  name: '',
  description: ''
}); 
  // 查询设施列表
  const getList = () => {
    loading.value = true;
    listFacilities(queryParams).then(response => {
      facilities.value = response.data;
      loading.value = false;
    });
  };
  
  // 结束创建设施
const endCreating = () => {
  isCreating.value = false;
};

// 开始创建设施
const startCreating = () => {
  isCreating.value = true;
  facilityVertices.value = []; // 清空之前的顶点
};




  // 检查点击位置是否在多边形内
  const isInsidePolygon = (x, y, polygon) => {
    let inside = false;
    const n = polygon.length;
    
    for (let i = 0, j = n - 1; i < n; j = i++) {
      const xi = polygon[i][0], yi = polygon[i][1];
      const xj = polygon[j][0], yj = polygon[j][1];
  
      const intersect = ((yi > y) !== (yj > y)) &&
        (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
      if (intersect) inside = !inside;
    }
    return inside;
  };
  
  // 检查点击位置是否在设施的多边形区域内
  const isInsideFacility = (x, y, facility) => {
    const coordinates = parseLocation(facility.location);
    return isInsidePolygon(x, y, coordinates);
  };
  
  // 处理点击事件
  const handleClick = (event) => {
    const x = event.offsetX;
    const y = event.offsetY;
    
    points.value.push({ x, y });
    
    const clickedFacility = facilities.value.find(facility => isInsideFacility(x, y, facility));
    if (clickedFacility) {
      alert(`Clicked on: ${clickedFacility.name}`);
    } else {
      console.log(`Clicked at coordinates: (${x}, ${y})`);
    }
    if (isCreating.value) {
    // const x = event.offsetX;
    // const y = event.offsetY;

    points.value.push({ x, y });
    facilityVertices.value.push([x, y]); // 存储设施的顶点

  }

  };
  // 提交设施
const submitFacility = () => {
    console.log('Submitting facility form:', facilityForm);
  const facilityData = {
    name: facilityForm.name,
    location: facilityVertices.value.map(v => `(${v[0]}, ${v[1]})`).join(', '),
    description: facilityForm.description
  };

  // TODO: 向后端提交 facilityData
  addFacility(facilityData).then(response => {
    console.log('Facility added:', response.data);
  });

  console.log('Submitting facility:', facilityData);
  isCreating.value = false; // 结束创建设施
  alert('设施添加成功');

  // 清空输入
  facilityName.value = '';
  points.value = [];
  facilityVertices.value = [];
  getList(); // 重新获取设施列表
};

  
  // 解析位置字符串为坐标数组
  const parseLocation = (location) => {
    location = location.replace(/['"\s]+/g, '');
    location = location.replace(/\[/g, '(').replace(/\]/g, ')');
    
    const matches = location.match(/\((\d+),(\d+)\)/g);
    return matches.map(match => match.replace(/[()]/g, '').split(',').map(Number));
  };
  
  // 根据设施的坐标计算样式
//   const getFacilityStyle = (facility) => {
//     const coordinates = parseLocation(facility.location);
//     const left = Math.min(...coordinates.map(coord => coord[0]));
//     const top = Math.min(...coordinates.map(coord => coord[1]));
//     const width = Math.max(...coordinates.map(coord => coord[0])) - left;
//     const height = Math.max(...coordinates.map(coord => coord[1])) - top;
  
//     return {
//       position: 'absolute',
//       left: left + 'px',
//       top: top + 'px',
//       width: width + 'px',
//       height: height + 'px',
//       backgroundColor: 'rgba(255, 0, 0, 0.3)', // 半透明背景
//       border: '1px solid red', // 红色边框
//       borderRadius: '1px'
//     };
//   };
// 根据设施的坐标计算样式
const getFacilityStyle = (facility) => {
  const coordinates = parseLocation(facility.location);
  if (!coordinates) {
    console.warn(`Invalid location for facility: ${facility.name}`);
    return {}; // 返回空样式以避免错误
  }

  // 获取多边形的边界
  const left = Math.min(...coordinates.map(coord => coord[0]));
  const top = Math.min(...coordinates.map(coord => coord[1]));
  const right = Math.max(...coordinates.map(coord => coord[0]));
  const bottom = Math.max(...coordinates.map(coord => coord[1]));

  // 计算多边形的宽度和高度
  const width = right - left;
  const height = bottom - top;

  // 使用 clipPath 定义多边形
  const polygonPoints = coordinates.map(coord => {
    return `${(coord[0] - left) / width * 100}% ${(coord[1] - top) / height * 100}%`;
  }).join(', ');

  return {
    position: 'absolute',
    left: left + 'px',
    top: top + 'px',
    width: width + 'px',
    height: height + 'px',
    backgroundColor: 'rgba(255, 0, 0, 0.3)', // 半透明背景
    border: '1px solid red', // 红色边框
    borderRadius: '1px',
    clipPath: `polygon(${polygonPoints})` // 使用 clipPath 定义多边形
  };
};
  
  // 获取图片尺寸
  const setImageDimensions = () => {
    const img = new Image();
    img.src = mapSrc;
    img.onload = () => {
      imageWidth.value = img.width;
      imageHeight.value = img.height;
    };
  };
  
  // 在组件挂载时获取图片尺寸
  onMounted(() => {
    setImageDimensions();
    getList();
  });
  </script>
  
  <style>
  .flex-container {
    display: flex;
    min-width: 1200px;
    max-width: 1600px;
    align-items: flex-start;
  }
  
  .map-container {
    position: relative;
    width: 1200px;
    height: auto;
  }
  
  .map-image {
    display: block;
    width: 1077px; /* 自适应宽度 */
    max-height: 100%; /* 适应容器 */
  }
  
  .marker {
    position: absolute;
    width: 10px;
    height: 10px;
    background-color: red;
    border-radius: 50%;
    transform: translate(-50%, -50%);
  }
  
  .facility {
    position: absolute;
    pointer-events: none; /* Disable pointer events for facilities */
  }
  
  .facility-name {
    color: white;
    font-weight: bold;
    font-size: 10px;
    text-align: center;
    margin-top: 5px;
    
  }
  .controls {
  margin-left: -20px;
  margin-top: 20px;
}
  </style>